package cn.iocoder.yudao.module.ym.service.connection;

import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleDO;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.UserRoleDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.dal.mysql.permission.RoleMapper;
import cn.iocoder.yudao.module.system.dal.mysql.permission.UserRoleMapper;
import cn.iocoder.yudao.module.system.dal.mysql.user.AdminUserMapper;
import cn.iocoder.yudao.module.ym.dal.dataobject.area.AreaDO;
import cn.iocoder.yudao.module.ym.dal.dataobject.site.SiteDO;
import cn.iocoder.yudao.module.ym.dal.mysql.area.AreaMapper;
import cn.iocoder.yudao.module.ym.dal.mysql.site.SiteMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import cn.iocoder.yudao.module.ym.controller.admin.connection.vo.*;
import cn.iocoder.yudao.module.ym.dal.dataobject.connection.ConnectionDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.ym.dal.mysql.connection.ConnectionMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.CONNECTION_NOT_EXISTS;

/**
 * 区域电站人员关联 Service 实现类
 *
 * @author 韩艳阳
 */
@Service
@Validated
public class ConnectionServiceImpl implements ConnectionService {

    @Resource
    private ConnectionMapper connectionMapper;

    @Resource
    private AreaMapper areaMapper;

    @Resource
    private SiteMapper siteMapper;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private AdminUserMapper adminUserMapper;

    @Override
    public Long createConnection(ConnectionSaveReqVO createReqVO) {
        // 插入
        ConnectionDO connection = BeanUtils.toBean(createReqVO, ConnectionDO.class);
        connectionMapper.insert(connection);
        // 返回
        return connection.getId();
    }

    @Override
    public Boolean insertBatch(List<ConnectionSaveReqVO> createReqVO) {
        List<ConnectionDO> connection = BeanUtils.toBean(createReqVO, ConnectionDO.class);

        return connectionMapper.insertBatch(connection);
    }

    @Override
    public void updateConnection(ConnectionSaveReqVO updateReqVO) {
        // 校验存在
        validateConnectionExists(updateReqVO.getId());
        // 更新
        ConnectionDO updateObj = BeanUtils.toBean(updateReqVO, ConnectionDO.class);
        connectionMapper.updateById(updateObj);
    }

    @Override
    public void deleteConnection(Long id) {
        // 校验存在
        validateConnectionExists(id);
        // 删除
        connectionMapper.deleteById(id);
    }

    private void validateConnectionExists(Long id) {
        if (connectionMapper.selectById(id) == null) {
            throw exception(CONNECTION_NOT_EXISTS);
        }
    }

    @Override
    public ConnectionDO getConnection(Long id) {
        return connectionMapper.selectById(id);
    }

    @Override
    public List<AdminUserDO> getPersonList() {
        List<AdminUserDO> adminUserDOS = new ArrayList<>();
        //查看当前用户是否有查看所有数据的权限
        Long loginUserId = getLoginUserId();
        Boolean flag = handleAll(loginUserId);
        if(flag){
            adminUserDOS = adminUserMapper.selectListByStatus(CommonStatusEnum.ENABLE.getStatus());
        }else {
            List<ConnectionDO> connectionDOS = connectionMapper.selectList(new LambdaQueryWrapper<ConnectionDO>()
                    .eq(ConnectionDO::getType, 1).eq(ConnectionDO::getPeopleId, loginUserId));
            Set<Long> collect = connectionDOS.stream().map(ConnectionDO::getPeopleId).collect(Collectors.toSet());
            if(!collect.isEmpty()){
                adminUserDOS = adminUserMapper.selectList(new LambdaQueryWrapper<AdminUserDO>()
                        .in(AdminUserDO::getId, collect).eq(AdminUserDO::getStatus,CommonStatusEnum.ENABLE.getStatus()));
            }
        }
        return adminUserDOS;
    }

    /**
     * 判断当前用户是否 管理员
     * @param userId
     * @return
     */
    public Boolean handleAll(Long userId){
        //判断当前用户得权限  如果是tenant_admin 则查看全部数据
        List<UserRoleDO> userRoleDOS = userRoleMapper.selectListByUserId(userId);
        if(userRoleDOS!=null && !userRoleDOS.isEmpty()){
            for (UserRoleDO userRoleDO : userRoleDOS) {
                Long roleId = userRoleDO.getRoleId();
                RoleDO roleDO = roleMapper.selectById(roleId);
                if(roleDO!=null && roleDO.getCode().equals("tenant_admin")){
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public PageResult<ConnectionRespVO> getConnectionPage(ConnectionPageReqVO pageReqVO) {
        PageResult<ConnectionRespVO> bean = BeanUtils.toBean(connectionMapper.selectPage(pageReqVO), ConnectionRespVO.class);
        List<ConnectionRespVO> list = bean.getList();
        if(list != null && !list.isEmpty()){
            List<AreaDO> areaDOList = areaMapper.selectList();
            Map<Long, AreaDO> areaMap = Optional.ofNullable(areaDOList)
                    .orElseGet(Collections::emptyList) // 处理null列表
                    .stream()
                    .collect(Collectors.toMap(
                            AreaDO::getId,  // Key提取器
                            Function.identity(),  // Value提取器（对象本身）
                            (oldValue, newValue) -> oldValue  // 处理重复键：保留第一个值
                    ));
            List<SiteDO> siteDOList = siteMapper.selectList();
            Map<Long, SiteDO> siteMap = Optional.ofNullable(siteDOList)
                    .orElseGet(Collections::emptyList) // 处理null列表
                    .stream()
                    .collect(Collectors.toMap(
                            SiteDO::getId,  // Key提取器
                            Function.identity(),  // Value提取器（对象本身）
                            (oldValue, newValue) -> oldValue  // 处理重复键：保留第一个值
                    ));

            for (ConnectionRespVO connectionRespVO : list) {
                Integer type = connectionRespVO.getType();
                if(type == 1){
                    AreaDO areaDO = areaMap.get(connectionRespVO.getThingId());
                    if(areaDO != null){
                        connectionRespVO.setThingName(areaDO.getAreaName());
                    }
                }else {
                    SiteDO siteDO = siteMap.get(connectionRespVO.getThingId());
                    if(siteDO != null){
                        connectionRespVO.setThingName(siteDO.getSiteName());
                    }
                }
            }
        }
        return bean;
    }

    @Override
    public List<ConnectionRespVO> getConnectionList(ConnectionPageReqVO pageReqVO) {
        List<ConnectionRespVO> result = new ArrayList<>();
        List<ConnectionRespVO> bean = BeanUtils.toBean(connectionMapper.selectList(pageReqVO), ConnectionRespVO.class);
        if(bean != null && !bean.isEmpty()){
            List<AreaDO> areaDOList = areaMapper.selectList();
            Map<Long, AreaDO> areaMap = Optional.ofNullable(areaDOList)
                    .orElseGet(Collections::emptyList) // 处理null列表
                    .stream()
                    .collect(Collectors.toMap(
                            AreaDO::getId,  // Key提取器
                            Function.identity(),  // Value提取器（对象本身）
                            (oldValue, newValue) -> oldValue  // 处理重复键：保留第一个值
                    ));
            List<SiteDO> siteDOList = siteMapper.selectList();
            Map<Long, SiteDO> siteMap = Optional.ofNullable(siteDOList)
                    .orElseGet(Collections::emptyList) // 处理null列表
                    .stream()
                    .collect(Collectors.toMap(
                            SiteDO::getId,  // Key提取器
                            Function.identity(),  // Value提取器（对象本身）
                            (oldValue, newValue) -> oldValue  // 处理重复键：保留第一个值
                    ));

            for (ConnectionRespVO connectionRespVO : bean) {
                Integer type = connectionRespVO.getType();
                if(type == 1){
                    AreaDO areaDO = areaMap.get(connectionRespVO.getThingId());
                    if(areaDO != null){
                        connectionRespVO.setThingName(areaDO.getAreaName());
                        result.add(connectionRespVO);
                    }
                }else {
                    SiteDO siteDO = siteMap.get(connectionRespVO.getThingId());
                    if(siteDO != null){
                        connectionRespVO.setThingName(siteDO.getSiteName());
                        result.add(connectionRespVO);
                    }
                }
            }
        }
        return bean;
    }


    @Override
    public Integer deleteByUserId(Long userId) {

        return connectionMapper.delete("people_id", String.valueOf(userId));
    }

    @Override
    public Set<Long> getUserAreaIdListByAreaId(Collection<Long> areaIds) {
        return convertSet(connectionMapper.selectListByAreaIds(areaIds), ConnectionDO::getPeopleId);
    }

}
